//
//  FindPrivateLetterVC.m
//  Find
//
//  Created by lanou3g on 15/10/29.
//  Copyright © 2015年 Reiko. All rights reserved.
//

#import "FindPrivateLetterVC.h"
#import "AppDelegate.h"
#define kConversationId @"55cd829e60b2b52cda834469"
#import "TextMessageTableViewCell.h"
#import "DetailView.h"
@interface FindPrivateLetterVC ()

@end

@implementation FindPrivateLetterVC

- (void)dealloc
{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (instancetype)init
{
    if (self = [super init]) {
        self.hidesBottomBarWhenPushed = YES;
    }
    return  self;
}
-(void)setTargetClientId:(NSString *)targetClientId{
    _targetClientId = targetClientId;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=[NSString stringWithFormat:@"与 %@ 的对话", self.targetClientId];
    
    self.messageTableView.delegate = self;
    self.messageTableView.dataSource = self;
    [self initMessageToolBar];
    [self.currentConversation queryMessagesWithLimit:kPageSize callback:^(NSArray *objects, NSError *error) {
        // 刷新 Tabel 控件，为其添加数据源
        [self.messages addObjectsFromArray:objects];
        [self.messageTableView reloadData];
    }];
    self.imClient.delegate = self;
    [self observeKeyboardNotification];
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Returns"] style:UIBarButtonItemStylePlain target:self action:@selector(actionBackButton:)];
    backButton.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backButton;
    
    
}
#pragma mark -- 点击方法
- (void)actionBackButton:(UIBarButtonItem *)sender{

    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark -- 监测键盘
- (void)observeKeyboardNotification{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)keyboardWillShow:(NSNotification *)notification{
    NSDictionary *userInfo = [notification userInfo];
    NSValue *keyboardValue = [userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGRect keyboardRect = [keyboardValue CGRectValue];
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    [self autoMoveKeyboard:keyboardRect time:animationDuration];
}
- (void)keyboardWillHide:(NSNotification *)notification{
    NSDictionary *userInfo = [notification userInfo];
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    [self autoMoveKeyboard:CGRectMake(0, 0, 0, 0) time:animationDuration];
}

- (void)autoMoveKeyboard:(CGRect)rect time:(NSTimeInterval)time{
    [UIView animateWithDuration:(time / 3) animations:^{
        self.messageToolBar.translatesAutoresizingMaskIntoConstraints = NO;
        [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.messageToolBar
                                                              attribute:NSLayoutAttributeTop
                                                              relatedBy:NSLayoutRelationEqual
                                                                 toItem:self.messageTableView
                                                              attribute:NSLayoutAttributeBottom
                                                             multiplier:1.0
                                                              constant:0.0]];
        [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.messageToolBar
                                                              attribute:NSLayoutAttributeLeft
                                                              relatedBy:NSLayoutRelationEqual
                                                                 toItem:self.messageTableView
                                                              attribute:NSLayoutAttributeLeft
                                                             multiplier:1.0
                                                               constant:0.0]];

       
        [self.messageToolBar updateConstraintsIfNeeded];
        [self.messageToolBar layoutIfNeeded];
        self.messageTableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight-rect.size.height- 130);
        
    }];
}


#pragma mark == 回收键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

#pragma mark -- 设置NavBar
- (void)addNavbar{
    self.edgesForExtendedLayout = UIRectEdgeNone;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [super tableView:tableView heightForRowAtIndexPath:indexPath];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TextMessageTableViewCell *cell= (TextMessageTableViewCell *)[super tableView:tableView cellForRowAtIndexPath:indexPath];
    AVIMMessage *message= self.messages[indexPath.row];
    // 判断是否为当前 ClientId 发送的消息，如果是，则该条消息会出现在列表的右侧
    BOOL isMe= [[AVIMClient defaultClient].clientId isEqualToString:message.clientId];   //
    if (isMe) {
        AVUser *user = [AVUser currentUser];
        NSString *urlString = [[user valueForKey:@"photoImage"] getThumbnailURLWithScaleToFit:NO width:100 height:100];
        [cell.userPhoto sd_setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:nil];
        
    } else{
        [cell.userPhoto sd_setImageWithURL:self.imageUrl placeholderImage:nil];
    }
    
    return cell;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
